package com.example.farmeri.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.farmeri.R;
import com.example.farmeri.data.DataParam;
import com.example.farmeri.data.config.DataConfig;
import com.example.farmeri.data.config.ServiceConfig;
import com.example.farmeri.pojo.MenuItem;
import com.example.farmeri.pojo.User;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 我的
 */
public class MineFragment extends Fragment {

    @BindView(R.id.fragment_mine_img)
    ImageView headImg;

    @BindView(R.id.fragment_mine_credit)
    TextView credit;

    @BindView(R.id.fragment_mine_adminImg)
    ImageView adminImg;

    @BindView(R.id.fragment_mine_nickname)
    TextView nickName;

    @BindView(R.id.fragment_mine_introduce)
    TextView introduce;

    static MineFragment fragment;

    @BindView(R.id.listView)
    ListView listView;

    //@BindView(R.id.fragment_mine_grid_view)
    //GridView gridView;
    List<Map<String,Object>> dataList;

    private Unbinder unbinder;
    public static MineFragment newInstance() {
        if (fragment == null){
            return new MineFragment();
        }
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        UserInfoViewModel model = new ViewModelProvider(requireActivity()).get(UserInfoViewModel.class);
//        model.getUserInfo().observe(getViewLifecycleOwner(),user -> {
//            nickName.setText(user.getNickName());
//            credit.setText(String.valueOf(user.getCredit()));
//            introduce.setText(user.getIntroduce());
//            adminImg.setVisibility(user.getIsAdmin()==0?View.GONE:View.VISIBLE);
//            headImg.setImageDrawable(getResources().getDrawable(R.drawable.head9));
//            if (user.getIcon()!=null){
//                Glide.with(getContext())
//                        .load(ServiceConfig.getRootPath(user.getIcon()))
//                        .into(headImg);
//            }
//        });

        String ident = DataParam.getUserInfo().getIdentity();
        if (ident.contains("后台管理员")){
            showMenu(DataConfig.adminMenus);
        }else if (ident.contains("农田主")){
            showMenu(DataConfig.farmerMenus);
        }else{
            showMenu(DataConfig.normalMenus);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        fillUserInfo(DataParam.getUserInfo());
    }

    private void fillUserInfo(User userInfo) {
        nickName.setText(DataParam.getUserInfo().getNick_name());
        credit.setText(String.valueOf(DataParam.getUserInfo().getCredit()));
        if (!TextUtils.isEmpty(DataParam.getUserInfo().getIntroduce())){
            introduce.setText(DataParam.getUserInfo().getIntroduce());
        }else {
            introduce.setText("该用户很懒，没有自我介绍");
        }
        adminImg.setVisibility(DataParam.getUserInfo().getIsAdmin()==0?View.GONE:View.VISIBLE);
        if (!TextUtils.isEmpty(DataParam.getUserInfo().getIcon())){
            Glide.with(getContext())
                    .load(ServiceConfig.getRootPath(DataParam.getUserInfo().getIcon()))
                    .into(headImg);
        }
    }


    private void showMenu(MenuItem[] items) {
        SimpleAdapter adapter = new SimpleAdapter(getContext(),
                getData(items),
                R.layout.item_mine_linear,
                new String[]{"img","title"},
                new int[]{R.id.item_mine_linear_image,R.id.item_mine_linear_text});
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            startActivity(new Intent(getContext(), items[position].menuClass));
        });
    }

    private List<? extends Map<String,?>> getData(MenuItem[] items) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (MenuItem item:items){
            Map<String ,Object> map = new HashMap<>();
            map.put("img",item.menuImg);
            map.put("title",item.menuTitle);
            list.add(map);
        }
        return list;
    }


    private void initUserInfo() {
        SharedPreferences sharedPre = getContext().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        nickName.setText(sharedPre.getString("nickName","暂无用户信息"));
        credit.setText(String.valueOf(sharedPre.getFloat("credit",0)));
        introduce.setText(sharedPre.getString("introduce","这个人很懒，什么都没有介绍"));
        adminImg.setVisibility(sharedPre.getInt("isAdmin",0)==0?View.GONE:View.VISIBLE);
        String  headImgUrl = ServiceConfig.getRootPath(sharedPre.getString("icon",null));
        Log.d("MineFragment", "initUserInfo: imgUrl = " + headImgUrl);;
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.head9)//图片加载出来前，显示的图片
                .circleCropTransform();
        Glide.with(getContext())
                .load(headImgUrl)
                .apply(options)
                .into(headImg);
    }


    //private void initData() {
    //    SimpleAdapter simpleAdapter = new SimpleAdapter(getContext(),
    //            getDataList(),
    //            R.layout.item_mine,
    //            new String[]{"title", "img"},
    //            new int[]{R.id.item_mine_text,R.id.item_mine_image});
    //    gridView.setAdapter(simpleAdapter);
    //}
    //
    //private List<Map<String ,Object>> getDataList(){
    //    dataList = new ArrayList<>();
    //    Map<String ,Object> map ;
    //    for (int i=0;i< DataConfig.mine_title.length;i++){
    //        map = new HashMap<>();
    //        map.put("title",DataConfig.mine_title[i]);
    //        map.put("img",DataConfig.mine_img[i]);
    //        dataList.add(map);
    //    }
    //    return dataList;
    //}

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        fragment = null;
    }
}
